<?php
namespace app\admin\controller\soft;
use app\admin\Adminbase;
require base_path().'/extend/base/files/PHPExeclCore.php';

class Nav extends Adminbase
{
    
    /**
    * 获取导航树数据
    * /admin/soft/nav/getTree
    * @access public
    * @param null 
    * @return  json
    */
    public function getTree(){
        $data= array();
        $result = Model('SystemNav')->getNavData( $userInfo["org_id"] );
        if($result[0]){
            foreach ($result as $key => $value) {
                array_push($data,$value);
            }
        }
        return $this -> ReSucess($data,"操作成功！");
    }
    
	//<!--  = 排序调整 =  -->
	//<!--  = /Admin/Nav/sortMove =  -->
	public function sortMove($moveId,$coverId){
		if( empty($moveId) )
			throw new \think\Exception('moveId参数不能为空');
		if( empty($coverId) )
			throw new \think\Exception('coverId参数不能为空');
		
		if($moveId==-1 || $coverId==-1){
			return $this->ReSucess("","操作成功");
		} 
		
		$result = model('SystemNav')->updateSort($moveId,$coverId);
		if($result){
			return $this->ReSucess("","操作成功");
		}else{
			return $this->ReError("未知错误！");
		}
		
	}
	
	//<!--  = 获取最后备份时间  =  -->
	//<!--  = /Admin/Nav/getLastBackupsDate =  -->
	public function getLastBackupsDate( $format="Y-m-d H:i:s" ){
		$result = model('nav','service')->getLastBackupsDate($format);
		if($result == -1){
			die( $this -> ReError("没有备份文件！") ); 
		};	
		if($result == -2){
			die( $this -> ReError("没有备份文件！") ); 
		};
		return $this->ReSucess( $result );	
	}
	
	//<!--  = 备份  =  -->
	//<!--  = /Admin/Nav/backups =  -->
	public function backups(){
		date_default_timezone_set('PRC');
		$date =  date('Y-m-d', time());
		mkdir("backup");
		mkdir("backup/pageMng"); //生成目录
		@unlink("backup/pageMng/$date.backups.xls");
		@unlink("backup/pageMng/$date.backups.action.xls");
		$this->exportExcel(true,"pageMng/$date.backups");
		$this->exportExcel(true,"pageMng/$date.backups.action","xw_system_nav_action");
		return $this->ReSucess("","备份成功！");
	}
	
	//<!--  = 还原  =  -->
	//<!--  = /Admin/Nav/reduction =  -->
	public function reduction(){
		$date = model('nav','service')->getLastBackupsDate('Y-m-d');
		if($date){
			$this->impNav("backup/pageMng/$date.backups.xls");
			$this->impNav("backup/pageMng/$date.backups.action.xls","xw_system_nav_action");
			return $this->ReSucess('','还原成功！');
		}else{
			return $this->ReError("没有备份文件！");
		}
	}
	
	//<!--  = 导出  =  -->
	//<!--  = /Admin/Nav/exportExcel =  -->
	public function exportExcel($isSaveLocal=false,$xlsName='nav_backups',$m="xw_system_nav"){
		$sqls="
			select column_name from information_schema.columns where table_name='$m';
		";
		$columnNames =\Db::query($sqls);
		
		$names=array();
		foreach($columnNames as $key => $name){
			array_push($names,$name['column_name']);
		}
		$names = array_unique($names);
		
		$Head = array();
		foreach($names as $key => $name){
			array_push($Head, array('value'=>"$name",'width'=>13) );
		}
	
		$xlsData  =  \Db::table($m) ->select();
		$data = array();
		foreach($xlsData as $key => $val){
			$arr=array();
			foreach($Head as $headVal){
				$fleid = $headVal['value'];
				array_push($arr,$val["$fleid"]);
			}
			array_push($data,$arr);
		}
		
		\PHPExeclCore::RecursionCreateExecl($xlsName,$Head,$data,$isSaveLocal);
	}

	//<!--  = 导入方法  =  -->
	//<!--  = /Admin/Nav/impNav =  -->
   	public function impNav($fileName,$m="xw_system_nav"){
		$data= \PHPExeclCore::getExcelData($fileName);
		$fields=implode(",",$data[1]);
		$sqls=array("truncate table $m");
		foreach ($data as $key => $value) {
			if($key>1){
				$arr=array();
				foreach ($data["$key"] as $val) {
					array_push($arr,"'".$val."'");
				}
				$values = implode(",",$arr);
				array_push($sqls,"INSERT INTO $m ($fields) VALUES ($values)");
			}
		}
		$sqls=implode(";",$sqls);
		db_multi_query($sqls); 
	}

	//<!--  = 导入  =  -->
	//<!--  = /Admin/Nav/importHandle =  -->
   	public function importHandle(){
   		$upload = new \Think\Upload();// 实例化上传类
   		$upload->autoSub = false; //自动生成子目录
	    $info   =   $upload->upload();
	    if(!$info) {
	    	return $this->ReError($upload->getError());				
	    }else{// 上传成功
	    	$savepath = "Backup/".$info["file"]["savepath"].$info["file"]["savename"];
	    	$this->impNav($savepath); 
	    	@unlink($savepath);//删除文件
	    	return $this->ReSucess('','导入成功！');
	    }
	}
	
	//<!--  = 插入初始权限 =  -->
	//<!--  = /Admin/insertAction  =  -->
	public function insertAction($nav_id='',$is_add_file='',$from_name=''){
        $data["nav_id"] = $nav_id; 
        $data["action_name"]='查询';
        $data["action_code"]='00';
        $result = model("SystemNavAction")->addAction($data);
        if(!$result){ return $this->ReError("错误！"); }
        
        //生成文件   
        (new PageCreate)->create($is_add_file,$from_name);

        return $this->ReSucess($result,"");
    }
	
	/**
    * 启用或禁用
    * /admin/user/addOrgData
    * @access public
    * @param array 	$data  [{user_id:1,is_enable:1,land_status:0}]
    * @return  json
    */
	public function setEnable($data){
		if( empty($data) )
			throw new \think\Exception('参数不能为空');
		
		$result =  model("SystemNav")->setEnable( $data );
		if(!$result){
			return $this -> ReError("操作失败！");
		}else{
			return $this -> ReSucess($result,"操作成功！");
		}
		
	}
	
	/**
    * 获取action_code流水号
    * /admin/nav/getSerialNumber
    * @access public
    * @param string 	$nav_id
    * @return  json
    */
	public function getSerialNumber($nav_id){
		$result = model("SystemNavAction")->where('nav_id',$nav_id)->max('action_code');
		$num = sprintf("%02d", $result + 1);
		return $this->ReSucess($num);
	}
	
}
